﻿using EvaluationSystem.Dto;
using EvaluationSystem.Models;
using EvaluationSystem.Models.Views;
using EvaluationSystem.Utils;
using EvaluationSystem.ViewModels;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EvaluationSystem.Controllers
{
    public class StudentController : BaseController<StudentController>
    {
        public StudentController(ILogger<StudentController> logger, MyDbContext dbContext) : base(logger, dbContext)
        {
        }

        public IActionResult Index([FromQuery] PageDto pageDto)
        {
            // 获取用户信息
            GetUserToken<People>(out var people);

            // 分页获取学生要评选的数据
            var pageInfoVm = pageDto.GetAutoPageList(people, () =>
                _dbContext.StudentCourse
                    .Include(t => t.TeacherWithCourses)
                    .ThenInclude(t => t.Teacher)
                    .Include(t => t.TeacherWithCourses)
                    .ThenInclude(t => t.Course)
                    .Include(t => t.Student)
                    .OrderByDescending(t => t.CreatedAt)
                    .Where(t => t.StudentId == people.PeopleId));

            // 获取通知信息
            var notify = _dbContext.Notifies.OrderByDescending(t => t.CreatedAt).FirstOrDefault();

            // 返回页面
            return View(pageInfoVm);
        }

        /// <summary>
        /// 评价页面
        /// </summary>
        /// <param name="scId">评价课程id</param>
        /// <returns></returns>
        public async Task<IActionResult> Evalution(int scId)
        {
            if (scId > 0)
            {
                GetUserToken<People>(out var person);

                // 查看该学生是否评价了这门课程
                var n = await _dbContext.StudentCourse.CountAsync(t => t.StudentId == person.PeopleId && t.ScId == scId && !String.IsNullOrEmpty(t.Evals));
                var vm = new EvalResultVM();
                if (n > 0)
                {
                    StudentEvalCourse? sec = await _dbContext.StudentCourse.FirstOrDefaultAsync(x => x.ScId == scId);
                    var text = sec?.Evals;
                    var ques = await _dbContext.Claim.ToListAsync();
                    List<QuesInfoVM> qinfos = ScoreUtil.GetQuesInfos(text, ques);

                    vm = new EvalResultVM
                    {
                        People = person,
                        QuesInfos = qinfos,
                        IsEvaluate = true,
                    };
                } // 判断是否已经评价过
                else
                {
                    var claims = await _dbContext.Claim.ToListAsync();

                    var ques = new List<QuesInfoVM>();
                    foreach (var claim in claims)
                    {
                        ques.Add(new QuesInfoVM()
                        {
                            Claim = claim,
                        });
                    }

                    vm = new EvalResultVM
                    {
                        People = person,
                        QuesInfos = ques
                    };

                } // 还没评价

                // 评论信息
                var comments = await _dbContext.Comment
                    .Include(t => t.Publisher)
                    .Include(t => t.Replier)
                    .Where(t => t.ScId == scId)
                    .Select(t => new CommentVm(t))
                    .ToListAsync();
                // 将评论信息添加到视图模型上
                vm.Comments = comments;

                return View(vm);
            } // 学生选课id
            else
            {
                return RedirectToAction("Index");
            } //选课id为空则返回主页
        }

        /// <summary>
        /// 学生选择授课页面
        /// </summary>
        /// <param name="pageDto"></param>
        /// <param name="tcid"></param>
        /// <returns></returns>
        public async Task<IActionResult> Select([FromQuery] PageDto pageDto, [FromQuery] int? tcid)
        {
            GetUserToken<People>(out var people);
            if (tcid.HasValue)
            {
                var isExist = await _dbContext.StudentCourse.AnyAsync(t => t.TeacherCourserId == tcid && t.StudentId == people.PeopleId);
                if (!isExist)
                {

                    StudentEvalCourse sc = new StudentEvalCourse
                    {
                        ScId = 0,
                        StudentId = people.PeopleId,
                        TeacherCourserId = tcid.Value,
                    };
                    await _dbContext.StudentCourse.AddAsync(sc);
                    var num = await _dbContext.SaveChangesAsync();
                    ViewData["msg"] = num > 0 ? "选择成功" : "选择失败";
                }
            }

            var tcids = await _dbContext.StudentCourse.Where(t => t.StudentId == people.PeopleId)
                .Select(t => t.TeacherCourserId).ToListAsync();

            PageDataVM<List<TeacherWithCourse>> pageDataVm = pageDto.GetAutoPageList<TeacherWithCourse>(people, () => _dbContext.TeacherCourse.Include(t => t.Course).Include(t => t.Teacher).Where(t => !tcids.Contains(t.TcId)));

            pageDataVm.RouteInfoVM = new RouteInfoVM("Select", "Student");

            return View(pageDataVm);
        }
    }
}
